package com.nrtech.brebes;

import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.loopj.android.http.*;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.MapView.LayoutParams;

public class MainActivity extends MapActivity implements LocationListener {
	 private LocationManager locManager;
	 private MapView mapView;
	 private MapController mapController;
	 private GeoPoint geoCoordinate;	
	 private Drawable markerImage;
	 private Drawable currentImage;
	
	 private Document xmlDoc;
	 private String xmlString;
	 private XMLParser parser;
	 private SimpleItemizedOverlay placePicOverlay;
	 private SimpleItemizedOverlay currentPicOverlay;
	 
	 List<Overlay> mapOverlays;
	 List<String> markerDescription;
		
	// All static variables
    static final String URL = "http://nrtech.org/maps/db.php";
    // XML node keys
    static final String KEY_ITEM = "area"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_LNG = "longitude";
    static final String KEY_LAT = "latitude";
    static final String KEY_NAME = "name";
    static final String KEY_DESC = "description";
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.mapZoom);  
        @SuppressWarnings("deprecation")
		View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
        
        mapOverlays = mapView.getOverlays();
        
        mapController = mapView.getController();
        String coordinates[] = {"-6.87212200", "109.04312600"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
        geoCoordinate = new GeoPoint(
                (int) (lat * 1E6), 
                (int) (lng * 1E6));
        
        mapController.animateTo(geoCoordinate);
        mapController.setZoom(11);        
        
        markerImage = this.getResources().getDrawable(R.drawable.pushpin);        
        placePicOverlay = new SimpleItemizedOverlay(markerImage, mapView, this);   
        
        AsyncHttpClient client = new AsyncHttpClient();        
        client.get(URL, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
            	try {            		
	            	System.out.println(response);
	                xmlString = response;
	                parser = new XMLParser();
	                xmlDoc = parser.getDomElement(xmlString); // getting DOM element
	                
	                NodeList nl = xmlDoc.getElementsByTagName(KEY_ITEM);
	                // looping through all item nodes <item>
	                for (int i = 0; i < nl.getLength(); i++) {
	                	Element e = (Element) nl.item(i);                    
	                	
	                	double latitude = Double.parseDouble(parser.getValue(e, KEY_LAT));
	                    double longitude = Double.parseDouble(parser.getValue(e, KEY_LNG));
	                    String id = parser.getValue(e, KEY_ID);
	                    String name = parser.getValue(e, KEY_NAME);
	                    String description = parser.getValue(e, KEY_DESC);
	                    	                    
	                    placePicOverlay.addOverlayItem(latitude, longitude, name, id, description);
	                }
                } catch (Exception ex) {
                	System.out.print(ex.getMessage());
                }
                
                mapView.getOverlays().add(placePicOverlay);
                mapView.invalidate();
            }
        });
        
        locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, this);
        //get the current location (last known location) from the location manager
        Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {       
        	currentImage = this.getResources().getDrawable(R.drawable.current);        
            currentPicOverlay = new SimpleItemizedOverlay(currentImage, mapView, this);
            String Desc = "Gunakan balon ini untuk menunjukan arah pergerakan anda";
            currentPicOverlay.addOverlayItem(location.getLatitude(), location.getLongitude(), "Anda di sini", "0", Desc);
        	mapView.getOverlays().add(currentPicOverlay);
            mapView.invalidate();
        }
	}
	
	private AlertDialog callAlert(String message) {
		AlertDialog builder = new AlertDialog.Builder(this).create();
    	builder.setTitle("Title");
    	builder.setMessage(message);
    	//builder.setPositiveButton("OK", null);
    	//AlertDialog dialog = builder.show();
    	builder.show();
    	return builder;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub	
		if(currentPicOverlay.size() > 0) {
			currentPicOverlay.removeItem(currentPicOverlay.size()-1);
		}
		String Desc = "Gunakan balon ini untuk menunjukan arah pergerakan anda";
		currentPicOverlay.addOverlayItem(location.getLatitude(), location.getLongitude(), "Anda di sini", "0", Desc);
    	mapView.getOverlays().add(currentPicOverlay);
        mapView.invalidate();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_settings:
	        	
	            return true;	        
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public boolean callInfoView(String mapId) {
		try {
			Intent intent = new Intent(this, InfoActivity.class);
			intent.putExtra("mapid", mapId);
			//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com")); 
			startActivity(intent);			
		} catch (Exception ex) {
			return false;
		}
		return true;
	}
}
